<?php
/**
 * about business basic message
 * edit by kim
 */
class b2c_ctl_admin_business_basicmsg extends desktop_controller{
	var $workground = 'b2c_ctl_admin_business';
	public function __construct($app)
    {
        parent::__construct($app);
		header("cache-control: no-store, no-cache, must-revalidate");
    }

	public function index(){
		$this->finder('b2c_mdl_business_basicmsg',array(
            'title'=>app::get('b2c')->_('基础信息'),
            'actions'=>array(
                         array('label'=>app::get('b2c')->_('添加供应商'),'href'=>'index.php?app=b2c&ctl=admin_business_basicmsg&act=addmsg','target'=>'dialog::{width:600,height:450,title:\''.app::get('b2c')->_('添加供应商').'\'}'),
	                     array('label'=>app::get('b2c')->_('禁用'),'submit'=>'index.php?app=b2c&ctl=admin_business_basicmsg&act=dis_enable','target'=>'refresh'),
	                     array('label'=>app::get('b2c')->_('解禁'),'submit'=>'index.php?app=b2c&ctl=admin_business_basicmsg&act=enable','target'=>'refresh')
                        ),
            'allow_detail_popup'=>true,
			'use_buildin_filter'=>true,
            'use_buildin_recycle'=>false,
            ));
	}

	function enable(){
		if(!$this->has_permission('batcheditmarketable')){
			$this->begin('');
			$this->end(false, app::get('b2c')->_('您无权操作'));
		}


		$this->begin('');
		if($_POST['isSelectedAll'] == '_ALL_'){
			$view_filter = $this->get_view_filter('b2c_ctl_admin_members','b2c_mdl_members');
			$_POST = array_merge($_POST,$view_filter);
			unset($_POST['isSelectedAll']);
		}
		$objMembers = app::get('pam')->model('members');
		$glist = $objMembers->setEnabled($_POST,'false');
		$this->end(true, app::get('b2c')->_('选中供应商已解禁'));
	}

	function dis_enable(){
		if(!$this->has_permission('batcheditmarketable')){
			$this->begin('');
			$this->end(false, app::get('b2c')->_('您无权操作'));
		}
		$this->begin('');
		if($_POST['isSelectedAll'] == '_ALL_'){
			$view_filter = $this->get_view_filter('b2c_ctl_admin_members','b2c_mdl_members');
			$_POST = array_merge($_POST,$view_filter);
			unset($_POST['isSelectedAll']);
		}
		$objMembers = app::get('pam')->model('members');
		$glist = $objMembers->setEnabled($_POST,'true',$msg);
		if(!$glist){
			$this->end(false, $msg);
		}else{
			$this->end(true, app::get('b2c')->_('选中供应商已禁用'));
		}
	}

	/*
     *本控制器公共分页函数
     * */
    function pagination($current,$totalPage,$act,$arg='',$app_id='b2c',$ctl='admin_business_basicmsg'){
        if (!$arg)
            $this->pagedata['pager'] = array(
                'current'=>$current,
                'total'=>$totalPage,
                'link' =>$this->gen_url(array('app'=>$app_id, 'ctl'=>$ctl,'act'=>$act,'args'=>array(($tmp = time())))),
                'token'=>$tmp,
                );
        else
        {
            $arg = array_merge($arg, array(($tmp = time())));
            $this->pagedata['pager'] = array(
                'current'=>$current,
                'total'=>$totalPage,
                'link' =>$this->gen_url(array('app'=>$app_id, 'ctl'=>$ctl,'act'=>$act,'args'=>$arg)),
                'token'=>$tmp,
                );
        }
    }

	function get_start($nPage,$count){
        $maxPage = ceil($count / $this->pagesize);
        if($nPage > $maxPage) $nPage = $maxPage;
        $start = ($nPage-1) * $this->pagesize;
        $start = $start<0 ? 0 : $start;
        $aPage['start'] = $start;
        $aPage['maxPage'] = $maxPage;
        return $aPage;
    }

	public function addmsg($member_lv_id=null){
		$member_lv=$this->app->model("member_lv");
        foreach($member_lv->getMLevel() as $row){
            $options[$row['member_lv_id']] = $row['name'];
        }
        $a_mem['lv']['options'] = is_array($options) ? $options : array(app::get('b2c')->_('请添加会员等级')) ;
        $attr = kernel::single('b2c_user_passport')->get_signup_attr();
        $this->pagedata['attr'] = $attr;
        $this->pagedata['mem'] = $a_mem;
		//手机区号前缀
		$phone_setting = $save_data['phone_setting'];
		$phones=app::get('b2c')->getConf('setting-phone.phone');
		$this->pagedata['phones'] = $phones;
		$this->display('admin/business/new.html');
	}

	function namecheck(){
        $userPassport = kernel::single('b2c_user_passport');
        if( !$userPassport->check_signup_account($_POST['pam_account']['login_name'],$message) ){
            echo json_encode(array('error'=>$message));exit;
        }
        echo json_encode(array('success'=>app::get('b2c')->_('该登录账号可用')));exit;
    }

    //添加供应商信息 连带着添加主账号
	public function add(){
		$this->begin('index.php?app=b2c&ctl=admin_business_basicmsg&act=index');
		$userPassport = kernel::single('b2c_user_passport');
		$member_model = app::get('b2c')->model('members');

		if( !$userPassport->check_signup_account($_POST['pam_account']['login_name'],$message) ){
		    $this->end(false, $message);
		}

		if(!$userPassport->check_passport($_POST['pam_account']['login_password'],$_POST['pam_account']['psw_confirm'],$message)){
		    $this->end(false, $message);
		}
        
        //供应商信息验证 此处暂未验证
        //$this->check_supplier($_POST['business'],$userPassport);

        $_POST["usertype"] = 1;
		$saveData = $_POST;
		$saveData = $userPassport->business_signup_process($saveData);
		$businessData = $_POST['business'];

		if($businessData){
			$businessData['check_time'] = strtotime($businessData['check_time']);

			//验证手机号及格式
			$mobile = trim($businessData['company_tel1']);
			$phone_setting = trim($businessData['phone_setting1']);
			$login_type = $userPassport->get_login_account_type($mobile);
			if($login_type != 'mobile'){
				$this->end(false,app::get('b2c')->_('请填写正确的手机号码'));
			}

			//判断手机号位数是否和符合配置区号内容
			$phones=app::get('b2c')->getConf('setting-phone.phone');
			foreach($phones as $v){
				if(in_array($phone_setting,$v)){
					$newarr = $v;
				}
			}
			$len = $newarr['length'];
			if((!preg_match('/^[1-9]\d{'.($len-1).'}$/', $mobile))){
				$this->end(false,app::get('b2c')->_('手机格式不正确'));
			}

			//判断手机号是否已经存在，包括区号相同
			/*
			$pamMembersModel = app::get('pam')->model('members');
			$list = $pamMembersModel -> getRow('phone_setting',array('login_account'=>$mobile,'login_type'=>'mobile'));
			$prefix = $list['phone_setting'];
			if($list || $phone_setting == $prefix){
				$this->end(false,app::get('b2c')->_('手机号码已存在'));
			}*/
			
			if($businessData['company_tel2']){
				$mobile2 = trim($businessData['company_tel2']);
				$phone_setting2 = trim($businessData['phone_setting2']);
				$login_type = $userPassport->get_login_account_type($mobile2);
				if($login_type != 'mobile'){
					$this->end(false,app::get('b2c')->_('请填写正确的手机号码'));
				}

				//判断手机号位数是否和符合配置区号内容
				$phones=app::get('b2c')->getConf('setting-phone.phone');
				foreach($phones as $v){
					if(in_array($phone_setting2,$v)){
						$newarr2 = $v;
					}
				}
				$len2 = $newarr2['length'];
				if((!preg_match('/^[1-9]\d{'.($len2-1).'}$/', $mobile))){
					$msg = $this->app->_('手机格式不正确');
					return false;
				}

				//判断手机号是否已经存在，包括区号相同
				/*
				$list = $pamMembersModel -> getRow('phone_setting',array('login_account'=>$mobile,'login_type'=>'mobile'));
				$prefix = $list['phone_setting'];
				if($list && $phone_setting2 == $prefix){
					$this->end(false,app::get('b2c')->_('手机号码已存在'));
				}*/
			}
		}
        if($_POST['is_main']){
            if( !$member_id = $userPassport->save_business1($saveData,$msg) ){
		        $this->end(false, app::get('b2c')->_('添加失败！'));
		    }
        }else{
            if( !$member_id = $userPassport->save_business($saveData,$businessData,$msg) ){
		        $this->end(false, app::get('b2c')->_($msg));
		    }
        }
		
		//增加会员同步 2012-5-15
		if( $member_rpc_object = kernel::service("b2c_member_rpc_sync") ) {
		    $member_rpc_object->createActive($member_id);
		}

		$this->end(true, app::get('b2c')->_('添加成功！'));
	}

    public function addson(){
        $b_id = trim($_GET['id']);
        $member_lv=$this->app->model("member_lv");
        foreach($member_lv->getMLevel() as $row){
            $options[$row['member_lv_id']] = $row['name'];
        }
        $a_mem['lv']['options'] = is_array($options) ? $options : array(app::get('b2c')->_('请添加会员等级')) ;
        $attr = kernel::single('b2c_user_passport')->get_signup_attr();
        $this->pagedata['attr'] = $attr;
        $this->pagedata['mem'] = $a_mem;
        $this->pagedata['bid'] = $b_id;
        $this->display('admin/business/addson.html');
    }

    //为供应商添加品牌操作
    public function save(){
        $this->begin();

        $aSave = $_POST['choice_brand'];
        $bid = $_POST['bid'];//供应商id
        if(empty($aSave)){
            $this->end( false,'保存失败！请选择至少一项品牌' );
        }

        $businessModel=$this->app->model("business_basicmsg");
        $return = $businessModel->save1($aSave,$bid);
        $this->end( true,'保存成功！' );
    }

    //修改供应商的基础信息
    public function edit(){
      $businessModel = $this->app->model('business_basicmsg');
        $bid = trim($_GET['bid']);
        $msg = $businessModel->getRow('*',array('business_id'=>$bid));
        $this->pagedata['msg'] = $msg;
		//手机区号前缀
		$phone_setting = $save_data['phone_setting'];
		$phones=app::get('b2c')->getConf('setting-phone.phone');
		$this->pagedata['phones'] = $phones;
        $this->singlepage('admin/business/business_message.html');
    }

    //此处只修改供应商信息
	public function editmsg(){
		ini_set("memory_limit","-1");
		$this->begin();
		$saveData = $_POST;
		$userPassport = kernel::single('b2c_user_passport');
        $businessModel = $this->app->model('business_basicmsg');
        $bbModel = $this->app->model('business_brand');
        $brandModel = $this->app->model('brand');
        $businessData = $_POST['business'];
        $goods_model = $this->app->model('goods');

        $businessData['check_time'] = strtotime($businessData['check_time']);
        $bid = $_POST['bid'];

		//验证手机号及格式
		$mobile = trim($businessData['company_tel1']);
		$phone_setting = trim($businessData['phone_setting1']);
		$login_type = $userPassport->get_login_account_type($mobile);
		if($login_type != 'mobile'){
			$this->end(false,app::get('b2c')->_('请填写正确的手机号码'));
		}

		//判断手机号位数是否和符合配置区号内容
		$phones=app::get('b2c')->getConf('setting-phone.phone');
		foreach($phones as $v){
			if(in_array($phone_setting,$v)){
				$newarr = $v;
			}
		}
		$len = $newarr['length'];
		if((!preg_match('/^[1-9]\d{'.($len-1).'}$/', $mobile))){
			$this->end(false,app::get('b2c')->_('手机格式不正确'));
		}

		//判断手机号是否已经存在，包括区号相同
		/*
		$pamMembersModel = app::get('pam')->model('members');
		$list = $pamMembersModel -> getRow('phone_setting',array('login_account'=>$mobile,'login_type'=>'mobile'));
		if($list && $list['phone_setting'] == $phone_setting){
			$this->end(false,app::get('b2c')->_('手机号码已存在11'));
		}*/
		
		if($businessData['company_tel2']){
			$mobile2 = trim($businessData['company_tel2']);
			$phone_setting2 = trim($businessData['phone_setting2']);
			$login_type = $userPassport->get_login_account_type($mobile2);
			if($login_type != 'mobile'){
				$this->end(false,app::get('b2c')->_('请填写正确的手机号码'));
			}

			//判断手机号位数是否和符合配置区号内容
			$phones=app::get('b2c')->getConf('setting-phone.phone');
			foreach($phones as $v){
				if(in_array($phone_setting2,$v)){
					$newarr2 = $v;
				}
			}
			$len2 = $newarr2['length'];
			if((!preg_match('/^[1-9]\d{'.($len2-1).'}$/', $mobile))){
				$msg = $this->app->_('手机格式不正确');
				return false;
			}
/*
			//判断手机号是否已经存在，包括区号相同
			$list = $pamMembersModel -> getRow('phone_setting',array('login_account'=>$mobile,'login_type'=>'mobile'));
			$prefix = $list['phone_setting'];
			if($list && $phone_setting2 == $prefix){
				$this->end(false,app::get('b2c')->_('手机号码已存在'));
			}*/
		}

		if($businessData['check_time']==''){
			$businessData['check_time'] = 0;
		}
        $bool = $businessModel->update($businessData,array('business_id'=>$bid));
        //供应商是否确认与品牌是否确认 20150808
        $is_share = $businessData['is_share'];
        $newarr = $bbModel->getList('brand_id',array('business_id'=>$bid));
        
        //如果供应商为true 则看品牌 othersize 什么都不用看
        if($is_share == 'true'){
            foreach($newarr as $k=>$v){
                $brands = $brandModel->getRow('brand_id,sto_confirm',array('brand_id'=>$v['brand_id']));
				if(!empty($brands)) {
					if ($brands['sto_confirm'] == 'Y') {
						$goods_model->update1(array('sto_confirm' => 'Y'), array('brand_id' => $brands['brand_id']));
						$sto = $goods_model->getRow('sto_confirm', array('brand_id' => $brands['brand_id']));
						if ($sto['sto_confirm'] == 'Y') {
							$goods_model->update1(array('goods_confirm' => 'Y'), array('brand_id' => $brands['brand_id']));
						} else {
							$goods_model->update1(array('goods_confirm' => 'N'), array('brand_id' => $brands['brand_id']));
						}
					} else {
						$goods_model->update1(array('goods_confirm' => 'N'), array('brand_id' => $brands['brand_id']));
					}
				}
            }
        }else{
            $goods_model->update1(array('goods_confirm'=>'N'),array('business_id'=>$bid));
        }

        if($bool){
            $this->end(true, app::get('b2c')->_('修改成功！'));
        }else {
			$this->end(false, app::get('b2c')->_('修改失败！'));
		}
	}

	//添加集货员
	public function save_operator(){
		$operatorModel=$this->app->model("business_operator");
		$this->begin();
		$aSave = $_POST['choice_operator'];
        $bid = $_POST['bid'];
        if(empty($aSave)){
            $this->end( false,app::get('b2c')->_('保存失败！请选择至少一个集货员'));
        }
		
		$ids = $operatorModel->getList('operator_id',array('business_id'=>$bid));

		if($ids){
			$operatorModel->delete(array('business_id'=>$bid));
		}

		foreach($aSave as $v){
			$data['operator_id'] = $v;
			$data["business_id"] = $bid;
			$data["register_time"] = time();
			$operatorModel->insert($data);
		}

        $this->end( true,'保存成功！' );
	}

}